﻿using MathNet.Numerics.Distributions;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XW.Utils;

namespace XW.Core
{
    public class SqlSugarCache : ICacheService
    {

        public void Add<V>(string key, V value)
        {
            CacheHelper.Set(key,value);
        }

        public void Add<V>(string key, V value, int cacheDurationInSeconds)
        {
            CacheHelper.Set(key, value, new Microsoft.Extensions.Caching.Distributed.DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow =   TimeSpan.FromSeconds(cacheDurationInSeconds) });
        }

        public bool ContainsKey<V>(string key)
        {
            return CacheHelper.ContainsKey(key);
        }

        public V Get<V>(string key)
        {
            return CacheHelper.Get<V>(key);
        }

        public IEnumerable<string> GetAllKey<V>()
        {
            return CacheHelper.AllKeys();
        }

        public V GetOrCreate<V>(string cacheKey, Func<V> create, int cacheDurationInSeconds = int.MaxValue)
        {
            if (CacheHelper.ContainsKey(cacheKey))
            {
                return CacheHelper.Get<V>(cacheKey);
            }
            else
            {
                var result = create();
                CacheHelper.Set(cacheKey, result, new Microsoft.Extensions.Caching.Distributed.DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(cacheDurationInSeconds) });
                return result;
            }
        }

        public void Remove<V>(string key)
        {
            CacheHelper.Remove(key);
        }
    }
}
